<?php
/**
 * User component for YAPP
 * Always extend from custom model
 */

// User types
define('USER_TYPE_NORMAL',           1);
define('USER_TYPE_ADMIN',            2);
define('USER_TYPE_SECURITY_MANAGER', 3);
define('USER_TYPE_MASTER',           4);

// User statuses
define('USER_STATUS_PENDING', 0);
define('USER_STATUS_ONLINE',  1);
define('USER_STATUS_OFFLINE', 2);

// Access log types
define('ACCESS_LOG_TYPE_LOGIN', 1);

// Class itself
class User extends CustomModel
{

    // Vars
    private $usersTable = 'users';
    private $userData   = false;
    private $loggedIn   = false;
    private $sessionKey = '__userComponentLogin__';

    // Login Admin with emails, users with username
    public function login($username, $password)
    {
        // Select from users and join profiles
        $user = $this->db->select(
                                    'users.*',
                                    'profiles.*'
                                 )
                                 ->from('users')
                                 ->join('profiles')
                                 ->on('users.iduser', '=', 'profiles.fkuser')
                                 ->where
                                 (
                                    filter
                                    (
                                        /*
                                        filter
                                        (
                                            filter('users.username', '=', $username),
                                            'AND',
                                            filter('users.password', '=', $password)
                                        ),
                                        */
                                        filter('users.username', '=', $username),
                                        'AND',
                                        filter
                                        (
                                            filter('user_type', '=', USER_TYPE_NORMAL),
                                            'AND',
                                            filter('user_status', '=', USER_STATUS_ONLINE)
                                        )
                                    ),
                                    'OR',
                                    filter
                                    (
                                        /*
                                        filter
                                        (
                                            filter('users.email', '=', $username),
                                            'AND',
                                            filter('users.password', '=', $password)
                                        ),
                                        */
                                        filter('users.email', '=', $username),
                                        'AND',
                                        filter
                                        (
                                            filter('user_type', '<>', USER_TYPE_NORMAL),
                                            'AND',
                                            filter('user_status', '=', USER_STATUS_ONLINE)
                                        )
                                    )
                                 )
                                 ->get(true);
        if ($user)
        {
            // Checkear password encriptada
            $registerModel = new RegisterModel();
            $encriptedPassword = $registerModel->encryptPassword($user['iduser'], $password);
            if ($encriptedPassword == $user['password'])
            {
                // Log in Class
                $this->loggedIn = true;
                $this->userData = $user;
                $logId = $this->saveAccesLog(ACCESS_LOG_TYPE_LOGIN);
                // Log in session
                if ($user['user_type'] != USER_TYPE_NORMAL)
                {
                    $user['pend_auth'] = true;
                }
                else
                {
                    $user['pend_auth'] = false;
                }
                $session = yappSession::getInstance();
                if ($session->set($this->sessionKey, $user))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }
        else
        {
            return false;
        }
    }

    // Check if pending logun authentication
    public function hasPendAuth()
    {
        return ($this->userData['pend_auth']);
    }

    // Get secret
    public function getSecret()
    {
        return ($this->userData['user_secret']);
    }

    // Auth was ok
    public function authOk()
    {
        $this->userData['pend_auth'] = false;
        $session = yappSession::getInstance();
        return $session->set($this->sessionKey, $this->userData);
    }

    // Save in access log
    public function saveAccesLog($accesType, $extraInfo = false)
    {
        if (!$this->loggedIn) return false;
        $abmLog = new ABM('access_log');
        $logId = $abmLog->insert(array(
            'fkuser'        => $this->userData['iduser'],
            'access_type'   => $accesType,
            'log_timestamp' => time(),
            'extra_info'    => $extraInfo,
        ));
        if ($logId)
        {
            return $logId;
        }
        else
        {
            return false;
        }
    }

    // Log from session (if actually logged)
    public function logFromSession()
    {
        $session = yappSession::getInstance();
        if ($userData = $session->get($this->sessionKey))
        {
            $this->userData = $userData;
            $this->loggedIn = true;
        }
        else
        {
            return false;
        }
    }

    // Check if user is logged
    public function isLoggedIn()
    {
        return $this->loggedIn;
    }

    // Check if user is normal
    public function isNormal()
    {
        return ($this->loggedIn && ($this->userData['user_type'] == USER_TYPE_NORMAL));
    }

    // Check if user is admin
    public function isAdmin()
    {
        return ($this->loggedIn && ($this->userData['user_type'] == USER_TYPE_ADMIN));
    }

    // Check if user is security
    public function isSecurity()
    {
        return ($this->loggedIn && ($this->userData['user_type'] == USER_TYPE_SECURITY_MANAGER));
    }

    // Check if user is master
    public function isMaster()
    {
        return ($this->loggedIn && ($this->userData['user_type'] == USER_TYPE_MASTER));
    }


    // Get user data
    public function getUserData()
    {
        return $this->userData;
    }

    // Get alias
    public function getAlias()
    {
        if (!empty($this->userData))
        {
            return $this->userData['username'];
        }
        else
        {
            return false;
        }
    }

    // Get id
    public function getId()
    {
        if (!empty($this->userData))
        {
            return $this->userData['iduser'];
        }
        else
        {
            return false;
        }
    }

    // Logout
    public function logout()
    {
        $this->loggedIn = false;
        $this->userData = false;
        $session = yappSession::getInstance();
        return $session->delete($this->sessionKey);
    }

}
?>